package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/users")
public class UserInfoController {

    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.appkey}")
    private String appKey;

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @RequestMapping("/get")
    public Object getUserById(String id){
        UserInfo userInfo = userInfoService.get(id);
        return userInfo;
    }

    @RequestMapping("/checkPhone")
    public Object checkPhone(String phone){
        Boolean b = userInfoService.checkPhone(phone);
        return b;
    }

    @RequestMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone, smsUrl, appKey);
        return JsonResult.success(null);
    }

    @PostMapping("/regist")
    public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode ){
        userInfoService.regist(phone, nickname, password, rpassword,verifyCode);
        return JsonResult.success();
    }

    @PostMapping("/login")
    public JsonResult<HashMap<String, Object>> login(String username, String password){
        UserInfo u = userInfoService.login(username, password);
        String token = userInfoRedisService.setToken(u);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", u);
        JsonResult<HashMap<String, Object>> ret = JsonResult.success(map);
        return ret;
    }



    @RequestMapping("/currentUser")
    public Object currentUser(HttpServletRequest req){
        //获取token
        String token = req.getHeader("token");
        //通过token到redis中查询用户数据
        UserInfo u = userInfoRedisService.getUserByToken(token);
        return JsonResult.success(u);
    }

}
